#include "mystring.h"
#include <stdlib.h>
#include <string.h>
#include <stdio.h>

// 安全复制字符串
char *mystrdup(const char *src)
{
    if (src == NULL)
        return NULL;
    size_t len = strlen(src) + 1;
    char *dest = (char *)malloc(len);
    if (dest == NULL)
    {
        perror("malloc failed in mystrdup");
        return NULL;
    }

    strcpy(dest, src);
    return dest;
}

// 安全连接字符串
char *mystrcat(char *dest, const char *src, size_t dest_size)
{
    if (dest == NULL || src == NULL || dest_size == 0)
    {
        return dest;
    }

    size_t dest_len = strlen(dest);
    size_t src_len = strlen(src);

    // 检查剩余空间是否足够（包括'\0'）
    if (dest_len + src_len + 1 > dest_size)
    {
        // 截断src以避免溢出
        src_len = dest_size - dest_len - 1;
    }

    strncat(dest, src, src_len);
    dest[dest_len + src_len] = '\0';
    return dest;
}

// 字符串分割
int mystrsplit(const char *str, char delim, char ***result)
{
    if (str == NULL || result == NULL)
        return 0;

    int count = 1;
    const char *p = str;
    while (*p)
    {
        if (*p == delim)
            count++;

        p++;
    }

    // 分配指针数组（+1给NULL哨兵）
    *result = (char **)malloc((count + 1) * sizeof(char *));
    if (*result == NULL)
    {
        perror("malloc failed in mystrsplit");
        return 0;
    }

    int i = 0;
    const char *start = str;
    p = str;
    while (1)
    {
        if (*p == delim || *p == '\0')
        {
            size_t len = p - start;
            (*result)[i] = (char *)malloc(len + 1);
            if ((*result)[i] == NULL)
            {
                perror("malloc failed for substring");
                // 清理已分配内存
                for (int j = 0; j < i; j++)
                    free((*result)[j]);
                free(*result);
                *result = NULL;
                return 0;
            }

            strncpy((*result)[i], start, len);
            (*result)[i][len] = '\0';
            i++;

            if (*p == '\0')
                break;
            start = p + 1;
        }
        p++;
    }

    (*result)[i] = NULL; // 以NULL结尾，方便遍历
    return count;
}

// 释放分割结果
void mystrsplit_free(char **parts, int count)
{
    if (parts == NULL)
        return;

    for (int i = 0; i < count; i++)
    {
        free(parts[i]);
    }
    free(parts);
}